package com.serkol.ams.controller.api;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.serkol.ams.bean.MyPageOld;
import com.serkol.ams.bean.Result;
import com.serkol.ams.entity.*;
import com.serkol.ams.modal.SqlFeildModal;
import com.serkol.ams.service.*;
import com.serkol.annotation.IsLogin;
import com.serkol.constant.AuthConstant;
import com.serkol.constant.ResultConstant;
import com.serkol.handler.MyLambdaQueryWrapper;
import com.serkol.utils.LangValidUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("api/agent")
public class AgentApiController {
    @Autowired
    private AgentService agentService;

    @Autowired
    private AgentInvitationRelationshipService invitationRelationshipService;


    @Autowired
    private AgentInvitationCategoryService invitationCategoryService;
    @Autowired
    private AgentRechangeLogService agentRechangeLogService;
    @Autowired
    private UsersService userService;
    @Value("${upload.path}")
    private String uploadpath;
    @Value("${upload.host}")
    private String uploadhost;
    @IsLogin
    @GetMapping("/findByList")
    public Result findByList() {
        AuthConstant.setPathUrl(uploadhost);
        LoginLog loginLog = AuthConstant.getLoginLog();
        Agent byId = agentService.getById(loginLog.getAgentId());


        MyLambdaQueryWrapper<Agent> query = new MyLambdaQueryWrapper<>();
        query.select(Agent::getId, Agent::getLevel, Agent::getName, Agent::getPrice, Agent::getState,Agent::getNameUg);
        query.picture(Agent::getImageId).as("url");
        query.orderByAsc(Agent::getLevel).lt(Agent::getLevel, byId.getLevel());

        List<Map<String, Object>> list = agentService.listMaps(query);
        return Result.ok(list);
    }

    @IsLogin
    @GetMapping("/findByParentList")
    public Result findByParentList() {
        LoginLog loginLog = AuthConstant.getLoginLog();
        System.out.println(loginLog);
     //   Users byUserId = userService.findByUserId(loginLog.getParentUserId());
     //   System.out.println(byUserId);
      //  Agent byId = agentService.getById(byUserId.getAgentId());
        QueryWrapper<Agent> query = new QueryWrapper<>();

        query.select(SqlFeildModal.getAgentFeild());
        query.lambda().orderByAsc(Agent::getLevel).eq(Agent::getState, 1);

        List<Agent> list = agentService.list(query);
        return Result.ok(list);
    }
    @IsLogin
    @GetMapping("/findByParentRegList")
    public Result findByParentRegList() {
        AuthConstant.setPathUrl(uploadhost);

        MyLambdaQueryWrapper<Agent> query = new MyLambdaQueryWrapper<>();
        query.select(Agent::getId, Agent::getLevel, Agent::getPrice, Agent::getState);
        query.picture(Agent::getImageId).as("url").langName(Agent::getName, Agent::getNameUg).as("name");
        query.orderByAsc(Agent::getLevel).eq(Agent::getState, 1);

        List<Map<String,Object>> list = agentService.listMaps(query);
        return Result.ok(list);
    }


    @IsLogin
    @GetMapping("/findByBackSelectList")
    public Result findByBackSelectList() {
        QueryWrapper<Agent> query = new QueryWrapper<>();
        query.select(SqlFeildModal.getAgentSelectFeild());
        query.lambda().orderByAsc(Agent::getLevel);
        List<Map<String, Object>> list = agentService.listMaps(query);
        return Result.ok(list);
    }

    @IsLogin
    //getAgentUserFeild
    @GetMapping("/findByMiniList")
    public Result findByMiniList(@RequestParam(name = "userId", defaultValue = "0") long userId) {
        Map<String, Object> agentMap = new HashMap<>();
        agentMap.put("ID", "AGENT_ID");
        MyLambdaQueryWrapper<Users> query = new MyLambdaQueryWrapper<>();
        query.groupBy(Users::getAgentId);
        query.select(Users::getAgentId).as("id");
        query.count(Users::getAgentId).as("count");
        query.otherTableColmuns("agent", LangValidUtils.getValid("ug", "IFNULL(NAME_UG,NAME)","NAME"), agentMap).as("name");

        LoginLog loginLog = AuthConstant.getLoginLog();
        if (userId == 0) {
            userId = loginLog.getUserId();
        }
        if(userId>0) {
            query.eq(Users::getParentUserId, userId);
        }

        List<Map<String, Object>> list = userService.listMaps(query);
        Long byUserCount = userService.findByUserCount(userId);
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("count", byUserCount);
        map.put("list", list);
        return Result.ok(map);
    }
    @GetMapping("/findByMiniAminList")
    public Result findByMiniAminList() {
        Map<String, Object> agentMap = new HashMap<>();
        agentMap.put("ID", "AGENT_ID");
        MyLambdaQueryWrapper<Agent> query = new MyLambdaQueryWrapper<>();
        query.select(Agent::getId,Agent::getPrice, Agent::getState)
                .langName(Agent::getName, Agent::getNameUg).as("name")
                .orderByAsc(Agent::getLevel);



        List<Map<String, Object>> list = agentService.listMaps(query);
        return Result.ok(list);
    }

    @IsLogin
    //getAgentUserFeild
    @GetMapping("/findByPerList")
    public Result findByPerList(@RequestParam(name = "userId", defaultValue = "0") long userId) {


        List<Map<String, Object>> list = agentService.findByPerList(userId);

        return Result.ok(list);
    }

    @IsLogin
    @GetMapping("/findByMiniSerachList")
    public Result findByMiniSerachList() {
        QueryWrapper<Agent> query = new QueryWrapper<>();

        query.select(SqlFeildModal.getAgentSelectTypeFeild());
        query.lambda().orderByAsc(Agent::getLevel);
        List<Map<String, Object>> list = agentService.listMaps(query);

        return Result.ok(list);
    }

    @IsLogin
    @GetMapping("/findByPageList")
    public Result findByPageList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current) {
        AuthConstant.setPathUrl(uploadhost);
        Result result = new Result();
       return agentService.findByList(pageSize, current);

    }

    //findByPageBackAgentReChangeList
    @IsLogin
    @GetMapping("/findByPageBackAgentReChangeList")
    public Result findByPageBackAgentReChangeList(@RequestParam(name = "pageSize", defaultValue = "10") int pageSize, @RequestParam(name = "current", defaultValue = "0") int current
            , @RequestParam(name = "userId", defaultValue = "0") long userId

    ) {

        Result result = new Result();
     return agentRechangeLogService.findByPageBackAgentReChangeList(pageSize,current, userId);

    }

    @IsLogin
    @RequestMapping("edit")
    public Result edit(@RequestBody Agent agent) {

        boolean b = false;
        if (agent.getId() != null && agent.getId() > 0) {
            b = agentService.updateById(agent);
        } else {
            b = agentService.save(agent);
        }
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);
    }

    @IsLogin
    @GetMapping("/findByPageInvitationList")
    public Result findByPageInvitationList(@RequestParam(name = "state", defaultValue = "0") int state,
                                           @RequestParam(name = "isActivty", defaultValue = "false") boolean isActivty) {
        Result result = new Result();
        List<Map<String, Object>> list = invitationRelationshipService.findByList(state,isActivty);

        result.setStatus(ResultConstant.SUCSESS);
        result.setData(list);

        return result;
    }
    @IsLogin
    @GetMapping("/findByPageInvitationCategoryIdList")
    public Result findByPageInvitationCategoryIdList(@RequestParam(name = "categoryId", defaultValue = "0") long categoryId,@RequestParam(name = "state", defaultValue = "0") int state,
                                           @RequestParam(name = "isActivty", defaultValue = "false") boolean isActivty) {
        Result result = new Result();
        List<Map<String, Object>> list = invitationRelationshipService.findByCategoryIdList(categoryId,state,isActivty);

        result.setStatus(ResultConstant.SUCSESS);
        result.setData(list);

        return result;
    }

    @IsLogin
    @PostMapping("invitationEdit")
    public Result invitationEdit(@RequestBody AgentInvitationRelationship agent) {


        boolean b = false;
        if (agent.getId() != null && agent.getId() > 0) {
            b = invitationRelationshipService.updateById(agent);
        } else {
            boolean bb = invitationRelationshipService.valid(agent);
            if (!bb) {
                b = invitationRelationshipService.save(agent);
            } else {
                return Result.failure(ResultConstant.FAIL);
            }
        }
        return b ? Result.ok() : Result.failure(ResultConstant.FAIL);

    }

    @IsLogin
    @GetMapping("/findByAgentInValidConfig")
    public Result findByAgentInValidConfig(
            @RequestParam(name = "agentId", defaultValue = "0") long agentId

    ) {


        AgentInvitationRelationship one = invitationRelationshipService.findByAgentInValidConfig(agentId);
        if (one != null) {
            return Result.ok(one);
        } else {
            return Result.failure();
        }

    }

    @IsLogin
    @GetMapping("/findInvitationCategoryByList")
    public Result findInvitationCategoryByList() {




        List<Map<String, Object>> list = invitationCategoryService.findByList();
        return Result.ok(list);
    }
    //agentCategoryState
    @IsLogin
    @PostMapping("/agentCategoryState")
    public Result agentCategoryState(  @RequestParam(name = "id", defaultValue = "0") long id){
        boolean data = invitationCategoryService.agentCategoryState(id);
        return data ? Result.ok() : Result.failure();
    }


}
